import cv2
import json
from glob import glob
import shutil
import os
import os.path as osp


label = '0'
root = r'D:\lliujian\DeepLearning\datasets\FPC镍片P60_20250227\16-37-40-700'
save_root = osp.join(r'D:\lliujian\DeepLearning\datasets\FPC镍片P60_20250227\16-37-40-700', osp.basename(root))
# save_root = '/home/aimall/workspace/VMsharedir/ciga/库存head/test/txt'
if not os.path.exists(save_root):
    os.makedirs(save_root)

for json_file in glob(root + '/*.json'):
    with open(json_file, 'r', encoding='utf-8') as f:
        jsondata = json.load(f)
    shapes = jsondata['shapes']
    img_name = jsondata['imagePath']
    h = jsondata['imageHeight']
    w = jsondata['imageWidth']
    with open(osp.join(save_root, osp.basename(json_file).replace('.json', '.txt')), 'w') as f2:
        for shp in shapes:

            point = shp['points']
            txt = (f"{label} {point[0][0] / w} {point[0][1] / h} {point[1][0] / w} {point[1][1] / h} "
                   f"{point[2][0] / w} {point[2][1] / h} {point[3][0] / w} {point[3][1] / h}\n")
            # txt = label + ' ' + str(point[0][0] / w) + ' ' + str(point[0][1] / h) + ' ' + str(
            #     point[1][0] / w) + ' ' + str(int(point[1][1])) + \
            #       ' ' + str(int(point[2][0])) + ' ' + str(int(point[2][1])) + ' ' + str(int(point[3][0])) + ' ' + str(
            #     int(point[3][1])) + '\n'
            f2.write(txt)
        shutil.copyfile(osp.join(root, img_name), osp.join(save_root, img_name))
